package com.og.converter;

import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import javax.inject.Inject;
import javax.inject.Named;

import org.apache.log4j.Logger;

import com.og.backingbean.Status;
import com.og.managedbean.ListBean;

/**
 * @author Renaud DIANA
 *
 */
@Named("statusConverterBean")
@SessionScoped
@FacesConverter("statusConverter")
public class StatusConverter implements Converter, Serializable {

	private static final long serialVersionUID = 1L;

	// Log4j	 
	private static final Logger	log	= Logger.getLogger(StatusConverter.class);
	
	/* Dependency injection */	
    // BackingBean	
	@Inject
    private ListBean list;
	
	/* -------------------- */
		
	/**
	 * Default constructor
	 */
	public StatusConverter() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		log.debug("String Value = " + value.toString());		
		if (value.equals("Select One")) {
            return null;
        }
		
        for (Status status : list.getListStatus()) {
            if (String.valueOf(status.getIdStatus()).equals(value)) { // !!equals method must be overridden in Application class!!
                return status;
            }
        }

        throw new ConverterException(new FacesMessage(String.format("Cannot convert %s to Status", value)));
    }

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object value) {
		log.debug("Object Value = " + value.toString());
		return (value instanceof Status) ? String.valueOf(((Status) value).getIdStatus()) : null;
	}
}
